﻿using UnityEngine;
using System.Collections;
using System;

public enum UDPEvent
{
    Initial = TCPEvent.MaxValue + 1,
    SendTo,
    MaxValue,
}

public class UDPMsg : MsgBase
{
    byte[] buffer;

    public ushort port;
    public int RecvBufferLength;

    public UdpSocket.UDPSocketDelegate recvDelegate;

    public UDPMsg(ushort msgID, ushort port, int recvLength, UdpSocket.UDPSocketDelegate tmpDelegate)
        : base(msgID)
    {
        this.port = port;
        this.recvDelegate = tmpDelegate;
        this.RecvBufferLength = recvLength;
    }

    public byte[] GetNetBytes()
    {
        return buffer;
    }
}

public class UDPSendMsg : MsgBase
{
    public byte[] buffer;

    public string ip;
    public ushort port;
    public int RecvBufferLength;

    public UDPSendMsg(ushort msgID, string ip, ushort port, byte[] buffer)
        : base(msgID)
    {
        this.ip = ip;
        this.port = port;
        this.buffer = buffer;
    }
}

public class FrameUDP : UIBase
{
    UdpSocket udpSocket;
    public override void ProcessEvent(MsgBase tmpMsg)
    {
        base.ProcessEvent(tmpMsg);



        switch ((UDPEvent)tmpMsg.msgId)
        {
            case UDPEvent.Initial:

                if (tmpMsg is UDPMsg)
                {
                    UDPMsg msg = (UDPMsg)tmpMsg;
                    udpSocket = new UdpSocket();
                    udpSocket.BindSocket(msg.port, msg.RecvBufferLength, msg.recvDelegate);
                }

                break;
            case UDPEvent.SendTo:

                if (tmpMsg is UDPSendMsg)
                {
                    UDPSendMsg msg = (UDPSendMsg)tmpMsg;
                    udpSocket.SendData(msg.ip, msg.buffer, msg.port);
                }
                break;
        }
    }

    void Awake()
    {
        msgIds = new ushort[]{
            (ushort)UDPEvent.Initial,
             (ushort)UDPEvent.SendTo,
        };

        RegistSelf(this, msgIds);
    }
}
